import json
import os
import re
import pandas as pd
from datetime import datetime
from docx import Document
from docx.text.paragraph import Paragraph
from docx.table import Table
from tabulate import tabulate
import ast

# 定义表格类型与核查规则的映射
TABLE_VALIDATION_RULES = {
    '表2-1': {
        '服务中心': {"column_index": 2, "rules": ["chinese"], "skip_header": True},
        '服务中文名称': {"column_index": 3, "rules": ["three_part_chinese"], "skip_header": True},
        '服务英文名称': {"column_index": 4, "rules": ["four_part_english"], "skip_header": True},
        '所属微服务英文名称': {"column_index": 5, "rules": ["service_naming"], "skip_header": True}
    },
    '表2-2': {
        '微服务中文名': {"column_index": 2, "rules": ["two_part_chinese"], "skip_header": True},
        '微服务英文名称': {"column_index": 3, "rules": ["service_naming"], "skip_header": True}
    },
    # 通用表3规则
    '表3-*': {
        '基本信息表': {
            '前端应用访问接口地址': {"field_name": "前端应用访问接口地址", "rules": ["path_format"]},
            '接口访问类型': {"field_name": "接口访问类型", "rules": ["http_method"]}
        },
        '请求参数表': {
            '入参示例': {"column_index": 7, "rules": ["json_input"], "only_first_row": True, "skip_header": True}
        },
        '返回参数表': {
            '出参示例': {"column_index": 6, "rules": ["json_output"], "only_first_row": True, "skip_header": True}
        }
    }
}

def clean_json_string(json_str):
    """清理JSON字符串中的多余空白和换行符"""
    if not json_str:
        return ""
    
    # 移除多余空白和换行符，但保留必要的结构
    cleaned = json_str.strip()
    
    # 修复常见JSON格式问题
    cleaned = cleaned.replace('\\', '\\\\')  # 转义反斜杠
    cleaned = cleaned.replace('\'', '"')     # 替换单引号为双引号
    
    # 移除行首和行尾的空白
    cleaned = re.sub(r'^\s+|\s+$', '', cleaned, flags=re.MULTILINE)
    
    # 修复键值对格式
    cleaned = re.sub(r'(\w)\s*:\s*', r'\1: ', cleaned)
    
    # 修复键名缺少双引号的问题
    cleaned = re.sub(r'([{,]\s*)(\w+)(\s*:)', r'\1"\2"\3', cleaned)
    
    # 修复值缺少双引号的问题
    cleaned = re.sub(r':\s*([a-zA-Z_][a-zA-Z0-9_]*)(\s*[,}])', r': "\1"\2', cleaned)
    
    # 移除多余的空格（保留换行符）
    cleaned = re.sub(r'[ \t]+', ' ', cleaned)
    
    return cleaned

def is_chinese(text):
    """检查文本是否为纯中文"""
    if not text or not isinstance(text, str):
        return False
    for char in text:
        if not ('\u4e00' <= char <= '\u9fff'):
            return False
    return True

def validate_chinese(column_data):
    """核查中文规则"""
    errors = []
    for i, value in enumerate(column_data):
        if not is_chinese(str(value)):
            errors.append({
                "row": i + 1,
                "value": str(value),
                "message": "不是纯中文"
            })
    return errors

def validate_three_part_chinese(column_data):
    """核查三段式中文命名"""
    errors = []
    for i, value in enumerate(column_data):
        parts = str(value).split('-')
        if len(parts) != 3 or not all(is_chinese(part) for part in parts):
            errors.append({
                "row": i + 1,
                "value": str(value),
                "message": "不符合5.2.2功能服务命名中【强制】功能服务中文命名，应采用三段式，体现其一级业务域、二级业务域，多级元素之间以短横线分隔。格式应为：一级业务域-二级业务域-服务中文名。"
            })
    return errors

def validate_two_part_chinese(column_data):
    """核查两段式中文命名"""
    errors = []
    for i, value in enumerate(column_data):
        parts = str(value).split('-')
        if len(parts) != 2 or not all(is_chinese(part) for part in parts):
            errors.append({
                "row": i + 1,
                "value": str(value),
                "message": "不符合5.2.3微服务命名中【强制】微服务中文命名，应采用两段式，体现所属一级业务域，名称中元素之间以短横线分隔。格式应为：一级业务域-微服务功能中文名。"
            })
    return errors

def validate_four_part_english(column_data):
    """核查四段式英文命名"""
    errors = []
    for i, value in enumerate(column_data):
        parts = str(value).split('-')
        if len(parts) < 3 or len(parts) > 5:
            errors.append({
                "row": i + 1,
                "value": str(value),
                "message": "不符合5.2.2功能服务命名中【强制】功能服务英文命名，应采用分段方式，多级元素之间以短横线分隔，最多为五段。其中前三段内容为固定格式，后两段由各业务中台按需定义。格式应为：一级业务域英文缩写-二级业务域英文缩写-服务英文名-xxx-xxx。"
            })
    return errors

def validate_service_naming(column_data):
    """核查微服务英文命名"""
    errors = []
    for i, value in enumerate(column_data):
        parts = str(value).split('-')
        if len(parts) > 5:
            errors.append({
                "row": i + 1,
                "value": str(value),
                "message": "不符合5.2.3微服务命名中【强制】微服务英文命名，应采用分段方式，应体现所属的一级业务域及微服务语义，多极元素之间以短横线分隔，最多为五段。其中第一段内容为固定格式，后四段由各业务中台按需定义。格式应为：一级业务域英文缩写-xxx-xxx-xxx-xxx。"
            })
    return errors

def validate_path_format(column_data):
    """核查接口路径格式（优化后）"""
    errors = []
    camel_case_pattern = re.compile(r'^[a-z]+(?:[A-Z][a-z]*)*$')  # 驼峰命名匹配
    
    for i, value in enumerate(column_data):
        path = str(value)
        path_errors = []
 
        # 检查是否包含非专业术语的数字
        path_parts = path.split('/')[1:]  # 跳过第一个空部分
        if any(re.search(r'\d', part) for part in path_parts if part):
            path_errors.append("接口路径包含非专业术语数字（规范5.3.1[3]）")
            
        # 检查各段是否为驼峰命名
        for part in path_parts:
            if not part:
                continue
            if not camel_case_pattern.match(part):
                path_errors.append(f"部分'{part}'不是合法的驼峰命名（推荐使用驼峰命名，规范5.3.1[2]）")
                
        # 检查最后一部分是否为动词+名词结构
        if len(path_parts) > 0:
            last_part = path_parts[-1]
            if not re.match(r'^[a-z]+[A-Z][a-z]+$', last_part):
                path_errors.append("最后部分应符合动词+名词结构（如 queryUser）")
        
        if path_errors:
            errors.append({
                "row": i + 1,
                "value": path,
                "message": " | ".join(path_errors)
            })
    
    return errors

def validate_http_method(column_data):
    """核查HTTP方法"""
    valid_methods = {'GET', 'POST', 'get', 'post'}
    errors = []
    for i, value in enumerate(column_data):
        method = str(value).strip()
        if method not in valid_methods:
            errors.append({
                "row": i + 1,
                "value": method,
                "message": "不是有效的HTTP方法(GET/POST)"
            })
    return errors

def validate_json_input(column_data):
    """核查入参JSON格式（优化后）"""
    errors = []
    valid_key_pattern = re.compile(r'^[a-zA-Z0-9_]+$')  # 禁止其他字符（规范5.3.3.1[1]）
    
    for i, value in enumerate(column_data):
        json_str = str(value).strip()
        if not json_str:
            continue  # 跳过空值
            
        json_errors = []
        try:
            # 清理JSON字符串
            cleaned_json = clean_json_string(json_str)
            
            # 尝试解析JSON
            data = json.loads(cleaned_json)
            
            if not isinstance(data, dict):
                json_errors.append("入参不是有效的JSON对象（规范5.3.3.3[1]）")
                
            # 检查参数命名规则
            for key in data.keys():
                # 检查字符合法性和长度
                if not valid_key_pattern.match(key):
                    json_errors.append(f"键'{key}': 包含非法字符（仅允许字母/数字/下划线，规范5.3.3.1[1]）")
                if len(key) > 64:
                    json_errors.append(f"键'{key}': 长度超过64个字符（规范5.3.3.1[1]）")
                
        except json.JSONDecodeError as e:
            # 提供更具体的错误信息
            error_msg = f"JSON解析错误 - {str(e)}"
            # 尝试修复常见问题后再次解析
            try:
                # 尝试修复常见的JSON格式问题
                fixed_json = cleaned_json.replace('\\', '\\\\')
                fixed_json = fixed_json.replace('\'', '"')
                fixed_json = re.sub(r'([{,]\s*)(\w+)(\s*:)', r'\1"\2"\3', fixed_json)  # 确保键在引号中
                fixed_json = re.sub(r':\s*(\w+)(\s*[,}])', r': "\1"\2', fixed_json)  # 确保字符串值在引号中
                
                # 再次尝试解析
                data = json.loads(fixed_json)
            except Exception as e2:
                json_errors.append(f"{error_msg}\n原始内容: {json_str[:100]}{'...' if len(json_str) > 100 else ''}")
        except Exception as e:
            json_errors.append(f"处理JSON时发生错误 - {str(e)}")
        
        if json_errors:
            errors.append({
                "row": i + 1,
                "value": json_str,
                "message": " | ".join(json_errors)
            })
    
    return errors

def validate_json_output(column_data):
    """核查出参JSON格式（优化后）"""
    errors = []
    valid_key_pattern = re.compile(r'^[a-zA-Z0-9_]+$')  # 禁止其他字符（规范5.3.4.1）
    required_fields = {'code', 'message', 'data'}  # 必须包含的字段（规范5.3.4.2[2]）
    
    for i, value in enumerate(column_data):
        json_str = str(value).strip()
        if not json_str:
            continue  # 跳过空值
            
        json_errors = []
        try:
            # 清理JSON字符串
            cleaned_json = clean_json_string(json_str)
            
            # 尝试解析JSON
            data = json.loads(cleaned_json)
            
            if not isinstance(data, dict):
                json_errors.append("出参不是有效的JSON对象（规范5.3.4.2[1]）")
                
            # 检查必要字段
            missing_fields = required_fields - set(data.keys())
            if missing_fields:
                json_errors.append(f"缺少必要字段: {', '.join(missing_fields)}（规范5.3.4.2[2]）")
                
            # 检查字段命名
            for key in data.keys():
                if not valid_key_pattern.match(key):
                    json_errors.append(f"键'{key}': 包含非法字符（仅允许字母/数字/下划线，规范5.3.4.1）")
                if len(key) > 64:
                    json_errors.append(f"键'{key}': 长度超过64个字符（规范5.3.4.1）")
                    
            # 检查code字段格式（规范5.3.4.3）
            code = data.get('code')
            if code is not None:
                if not isinstance(code, str):
                    json_errors.append(f"code字段'{code}': 必须为字符串类型（规范5.3.4.3[2]）")
                elif not re.match(r'^\d{6}$', code):
                    json_errors.append(f"code字段'{code}': 应为6位数字字符串（规范5.3.4.3[2]）")
                # 业务返回码需添加一级业务域前缀（示例：假设当前中台为emss）
                elif len(code) > 6 and not code.startswith(('pgp', 'pmp', 'emss', 'fmp')):
                    json_errors.append(f"code字段'{code}': 业务返回码需以一级业务域缩写开头（规范5.3.4.3[3]）")
                    
            # 检查message字段（规范5.3.4.2[2]）
            message = data.get('message')
            if message is not None and not isinstance(message, str):
                json_errors.append(f"message字段'{message}': 必须为字符串类型")
                
        except json.JSONDecodeError as e:
            # 提供更具体的错误信息
            error_msg = f"JSON解析错误 - {str(e)}"
            # 尝试修复常见问题后再次解析
            try:
                # 尝试修复常见的JSON格式问题
                fixed_json = cleaned_json.replace('\\', '\\\\')
                fixed_json = fixed_json.replace('\'', '"')
                fixed_json = re.sub(r'([{,]\s*)(\w+)(\s*:)', r'\1"\2"\3', fixed_json)  # 确保键在引号中
                fixed_json = re.sub(r':\s*(\w+)(\s*[,}])', r': "\1"\2', fixed_json)  # 确保字符串值在引号中
                
                # 再次尝试解析
                data = json.loads(fixed_json)
            except Exception as e2:
                json_errors.append(f"{error_msg}\n原始内容: {json_str[:100]}{'...' if len(json_str) > 100 else ''}")
        except Exception as e:
            json_errors.append(f"处理JSON时发生错误 - {str(e)}")
        
        if json_errors:
            errors.append({
                "row": i + 1,
                "value": json_str,
                "message": " | ".join(json_errors)
            })
    
    return errors

# 核查规则映射
VALIDATION_RULES_MAP = {
    "chinese": validate_chinese,
    "three_part_chinese": validate_three_part_chinese,
    "two_part_chinese": validate_two_part_chinese,
    "four_part_english": validate_four_part_english,
    "service_naming": validate_service_naming,
    "path_format": validate_path_format,
    "http_method": validate_http_method,
    "json_input": validate_json_input,
    "json_output": validate_json_output
}

def read_docx_tables(docx_file):
    print(f"正在处理文档: {os.path.abspath(docx_file)}")
    doc = Document(docx_file)
    
    if not os.path.exists(docx_file):
        raise FileNotFoundError(f"文档文件不存在: {docx_file}")
    
    document_data = {
        "version": "1.0",
        "document": os.path.basename(docx_file),
        "sections": [],
        "generated_at": datetime.now().isoformat()
    }
    
    # 创建一个默认章节用于存储所有表格
    default_section = {
        "title": "所有表格",
        "tables": []
    }
    document_data["sections"].append(default_section)
    
    current_table_title = None
    
    elements = list(doc.element.body.iterchildren())
    
    for idx, element in enumerate(elements):
        if element.tag.endswith('p'):
            para = Paragraph(element, doc)
            text = para.text.strip()
            
            # 捕获表格标题
            if idx+1 < len(elements) and elements[idx+1].tag.endswith('tbl'):
                # 增强表格标题识别
                if re.match(r'^(表|表格|Table)\s*\d+[-\.]?\d*', text):
                    current_table_title = text
                elif re.search(r'(信息|参数|清单|接口|功能|服务)(表)?$', text, re.IGNORECASE):
                    current_table_title = text
                else:
                    current_table_title = f"未命名表格_{idx}"
                print(f"识别到表格: {current_table_title}")

        # 处理表格
        elif element.tag.endswith('tbl') and current_table_title:
            print(f"正在处理表格: {current_table_title}")
            try:
                table = Table(element, doc)
                table_data = parse_table(table)
                
                if not table_data or not any(any(cell for cell in row) for row in table_data):
                    print("警告: 空表格数据")
                    continue
                
                # 确定表格类型
                table_type = extract_table_number(current_table_title)
                
                # 确定表格类别
                table_category = "未知"
                if table_type == "表2-1":
                    table_category = "功能服务清单"
                elif table_type == "表2-2":
                    table_category = "微服务清单"
                elif table_type.startswith("表3-"):
                    # 使用正则表达式匹配表3的具体类型
                    if re.search(r'基本信息表', current_table_title):
                        table_category = "基本信息表"
                    elif re.search(r'请求参数(信息)?表', current_table_title):
                        table_category = "请求参数表"
                    elif re.search(r'返回参数(信息)?表', current_table_title):
                        table_category = "返回参数表"
                    else:
                        table_category = "其他表3表格"
                    
                    print(f"表3表格分类: {table_category} (编号: {table_type})")
                else:
                    table_category = table_type
                
                # 处理表格数据
                processed_table = process_table_data(table_data, table_type, table_category, current_table_title)
                
                # 执行标准化核查 - 对所有表格进行核查
                validation_results = {}
                
                # 获取适用的核查规则
                table_rules = TABLE_VALIDATION_RULES.get(table_type, {})
                
                # 特殊处理表3-*的规则
                if table_type.startswith("表3-") and '表3-*' in TABLE_VALIDATION_RULES:
                    # 获取表3-*的特定类别规则
                    category_rules = TABLE_VALIDATION_RULES.get('表3-*', {}).get(table_category, {})
                    table_rules.update(category_rules)
                
                if table_rules:
                    print(f"开始执行表格标准化检查，表格类型: {table_type}，表格类别: {table_category}")
                    
                    # 获取原始表格数据
                    raw_data = processed_table.get("raw_data", [])
                    processed_data = processed_table.get("data", [])
                    
                    if raw_data or processed_data:
                        # 执行核查
                        for col_name, rule_config in table_rules.items():
                            print(f"  正在检查列: {col_name}")
                            rules = rule_config["rules"]
                            col_data = []
                            
                            # 提取列数据
                            if "column_index" in rule_config:
                                col_index = rule_config["column_index"] - 1  # 修正：转换为0-based索引
                                
                                # 跳过表头行
                                start_index = 1 if rule_config.get("skip_header", False) else 0
                                
                                for row in raw_data[start_index:]:
                                    if col_index < len(row):
                                        col_data.append(row[col_index])
                                    else:
                                        col_data.append("")
                                        
                                # 只取第一行数据
                                if rule_config.get("only_first_row", False) and col_data:
                                    col_data = [col_data[0]]
                                    
                            elif "field_name" in rule_config and processed_data:
                                field_name = rule_config["field_name"]
                                for row in processed_data:
                                    if field_name in row:
                                        col_data.append(row[field_name])
                                    else:
                                        col_data.append("")
                            
                            # 应用所有规则
                            col_errors = {}
                            for rule in rules:
                                if rule in VALIDATION_RULES_MAP:
                                    rule_errors = VALIDATION_RULES_MAP[rule](col_data)
                                    if rule_errors:
                                        col_errors[rule] = rule_errors
                            
                            # 保存结果
                            if col_errors:
                                validation_results[col_name] = col_errors
                            else:
                                validation_results[col_name] = "所有数据符合规范"
                            
                            print(f"    检查完成，发现错误: {len(col_errors)}" if col_errors else "    检查完成，无错误")
                    else:
                        print(f"  警告: 表格 {table_type} 无有效数据，跳过检查")
                    
                    print(f"表格 {table_type} 标准化检查完成")
                    
                    # 将验证结果附加到表格数据中
                    processed_table["validation_results"] = validation_results
                else:
                    print(f"表格 {table_type} 没有配置核查规则，跳过检查")

                # 存储处理结果
                default_section["tables"].append(processed_table)
            except Exception as e:
                print(f"处理表格时出错: {str(e)}")
                continue
            
            current_table_title = None  # 重置表格标题

    # 原有 output.json 写入逻辑
    output_path = os.path.join(
        os.path.dirname(docx_file),
        f"{os.path.splitext(os.path.basename(docx_file))[0]}_output.json"
    )
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(document_data, f, ensure_ascii=False, indent=2)

    # 新增 testResults.json 写入逻辑（提取验证结果）
    test_results = {
        "version": "1.0",
        "document": os.path.basename(docx_file),
        "generated_at": datetime.now().isoformat(),
        "validation_errors": [],
        "total_errors": 0  # 初始化总错误数
    }
    
    # 遍历所有表格收集验证错误
    total_errors_count = 0  # 统计总错误数
    for section in document_data["sections"]:
        for table in section.get("tables", []):
            table_type = table.get("table_type", "未知类型")
            table_errors = table.get("validation_results", {})
            
            # 只处理有错误结果的表格
            if not table_errors:
                continue
                
            # 按列处理错误
            for col_name, col_results in table_errors.items():
                if col_results == "所有数据符合规范":
                    continue
                    
                # 按规则处理错误
                for rule_name, rule_errors in col_results.items():
                    # 汇总相同错误消息的行号和值
                    error_groups = {}
                    for error in rule_errors:
                        msg = error["message"]
                        if msg not in error_groups:
                            error_groups[msg] = {
                                "rows": [],
                                "values": []
                            }
                        error_groups[msg]["rows"].append(error["row"])
                        error_groups[msg]["values"].append(error["value"])
                    
                    # 转换为输出格式
                    for msg, data in error_groups.items():
                        error_entry = {
                            "table_type": table_type,
                            "column": col_name,
                            "rule": rule_name,
                            "error_message": msg,
                            "rows": data["rows"],
                            "values": data["values"]
                        }
                        test_results["validation_errors"].append(error_entry)
                        total_errors_count += 1
    
    # 记录总错误数
    test_results["total_errors"] = sum(len(error["rows"]) for error in test_results["validation_errors"])

    test_results_path = os.path.join(
        os.path.dirname(docx_file),
        f"{os.path.splitext(os.path.basename(docx_file))[0]}_testResults.json"
    )
    with open(test_results_path, 'w', encoding='utf-8') as f:
        json.dump(test_results, f, ensure_ascii=False, indent=2)

    return document_data

def parse_table(table):
    """解析表格数据，处理合并单元格"""
    data = []
    # 创建一个网格来存储单元格值
    grid = []
    for i, row in enumerate(table.rows):
        grid_row = []
        for cell in row.cells:
            # 获取单元格文本，去除多余空格
            cell_text = cell.text.strip()
            grid_row.append({
                'value': cell_text,
                'rowspan': 1,
                'colspan': 1
            })
        grid.append(grid_row)
    
    # 处理跨行和跨列
    for i, row in enumerate(table.rows):
        for j, cell in enumerate(row.cells):
            # 处理列合并
            if hasattr(cell, '_tc') and hasattr(cell._tc, 'grid_span'):
                colspan = cell._tc.grid_span
                if colspan > 1:
                    grid[i][j]['colspan'] = colspan
                    # 清空被合并的单元格
                    for k in range(1, colspan):
                        if j+k < len(grid[i]):
                            grid[i][j+k]['value'] = ""
            
            # 处理行合并
            if hasattr(cell, '_tc') and hasattr(cell._tc, 'vMerge'):
                if cell._tc.vMerge == "restart":
                    # 计算行合并范围
                    rowspan = 1
                    for k in range(i+1, len(grid)):
                        if j < len(grid[k]) and grid[k][j]['value'] == "":
                            rowspan += 1
                        else:
                            break
                    grid[i][j]['rowspan'] = rowspan
                    # 清空被合并的单元格
                    for k in range(1, rowspan):
                        if i+k < len(grid) and j < len(grid[i+k]):
                            grid[i+k][j]['value'] = ""
    
    # 生成最终表格数据
    for i, row in enumerate(grid):
        data_row = []
        for j, cell in enumerate(row):
            if cell['value']:  # 只添加有值的单元格
                data_row.append(cell['value'])
        if data_row:  # 只添加非空行
            data.append(data_row)
    
    return data

def extract_table_number(title):
    """从表格标题中提取纯表格编号（如"表2-1"）"""
    if not title:
        return "未知表格"
    match = re.search(r'(表\d+[-\.]?\d*)', title)
    return match.group(1) if match else title

def process_table_data(table_data, table_type, table_category, title):
    """处理表格数据，根据表格类型采用不同处理方式"""
    # 基本信息表处理
    if table_category == "基本信息表" or table_type.startswith("表3-") and "基本信息表" in table_category:
        result = process_vertical_table(table_data, title)
    # 请求参数表处理
    elif table_category == "请求参数表" or table_type.startswith("表3-") and "请求参数表" in table_category:
        result = process_request_parameters_table(table_data, title)
    # 返回参数表处理
    elif table_category == "返回参数表" or table_type.startswith("表3-") and "返回参数表" in table_category:
        result = process_response_parameters_table(table_data, title)
    # 其他表格处理
    else:
        result = process_general_table(table_data, title)
    
    # 保存原始表格数据
    result["raw_data"] = table_data
    result["table_type"] = extract_table_number(title)
    result["table_category"] = table_category
    return result

def process_general_table(table_data, title):
    """处理普通表格"""
    if not table_data or not any(any(cell for cell in row) for row in table_data):
        return {"table_type": extract_table_number(title)}
    
    # 清洗表头
    raw_headers = table_data[0]
    cleaned_headers = [header.strip() for header in raw_headers]
    headers = [cell if cell else f"列_{i+1}" for i, cell in enumerate(cleaned_headers)]
    
    # 生成数据
    return {
        "headers": headers,
        "data": [
            dict(zip(headers, [str(cell).strip() if cell else "" for cell in row]))
            for row in table_data[1:] if any(cell.strip() for cell in row)
        ],
        "raw_data": table_data  # 保存原始数据
    }

def process_vertical_table(table_data, title):
    """处理纵向表格（如基本信息表）"""
    result = {}
    
    # 处理纵向表格数据
    data_dict = {}
    for row in table_data:
        if len(row) >= 2 and row[0].strip() and row[1].strip():
            key = row[0].strip()
            value = row[1].strip()
            data_dict[key] = value
    
    # 转换为横向格式
    headers = list(data_dict.keys())
    values = list(data_dict.values())
    
    result["headers"] = headers
    result["data"] = [dict(zip(headers, values))]
    result["raw_data"] = table_data  # 保存原始数据
    
    return result

def process_request_parameters_table(table_data, title):
    """处理请求参数表（表3-2, 表3-5等）"""
    result = {}
    
    if not table_data or len(table_data) < 2:
        return result
    
    # 提取表头
    headers = [cell.strip() for cell in table_data[0]]
    
    # 查找入参示例行
    param_example = ""
    param_example_row_index = -1
    
    # 寻找包含"入参示例"的行，允许有空格和换行
    for i, row in enumerate(table_data):
        for cell in row:
            # 使用正则表达式匹配，忽略空格和换行
            if re.search(r'入\s*参\s*示\s*例', cell, re.IGNORECASE):
                param_example_row_index = i
                break
        if param_example_row_index != -1:
            break
    
    # 如果找到入参示例行
    if param_example_row_index != -1:
        # 获取示例内容
        if param_example_row_index + 1 < len(table_data):
            # 合并示例行的所有单元格内容
            param_example = " ".join(table_data[param_example_row_index + 1]).strip()
        
        # 移除示例行和内容行
        table_data = [
            row for idx, row in enumerate(table_data)
            if idx != param_example_row_index and idx != param_example_row_index + 1
        ]
    
    # 添加入参示例列（如果需要）
    if "入参示例" not in headers:
        headers.append("入参示例")
    
    # 生成数据行
    data = []
    for i, row in enumerate(table_data[1:]):
        # 确保行长度与表头一致
        while len(row) < len(headers):
            row.append("")
            
        # 创建行字典
        row_dict = dict(zip(headers, row))
        
        # 如果是第一行，添加入参示例
        if i == 0 and param_example:
            row_dict["入参示例"] = param_example
        
        data.append(row_dict)
    
    result["headers"] = headers
    result["data"] = data
    result["raw_data"] = table_data  # 保存原始数据
    return result

def process_response_parameters_table(table_data, title):
    """处理返回参数表（表3-3, 表3-6等）"""
    result = {}
    
    if not table_data or len(table_data) < 2:
        return result
    
    # 提取表头
    headers = [cell.strip() for cell in table_data[0]]
    
    # 查找出参示例行
    response_example = ""
    response_example_row_index = -1
    
    # 寻找包含"出参示例"的行，允许有空格和换行
    for i, row in enumerate(table_data):
        for cell in row:
            # 使用正则表达式匹配，忽略空格和换行
            if re.search(r'出\s*参\s*示\s*例', cell, re.IGNORECASE):
                response_example_row_index = i
                break
        if response_example_row_index != -1:
            break
    
    # 如果找到出参示例行
    if response_example_row_index != -1:
        # 获取示例内容
        if response_example_row_index + 1 < len(table_data):
            # 合并示例行的所有单元格内容
            response_example = " ".join(table_data[response_example_row_index + 1]).strip()
        
        # 移除示例行和内容行
        table_data = [
            row for idx, row in enumerate(table_data)
            if idx != response_example_row_index and idx != response_example_row_index + 1
        ]
    
    # 添加出参示例列（如果需要）
    if "出参示例" not in headers:
        headers.append("出参示例")
    
    # 生成数据行
    data = []
    for i, row in enumerate(table_data[1:]):
        # 确保行长度与表头一致
        while len(row) < len(headers):
            row.append("")
            
        # 创建行字典
        row_dict = dict(zip(headers, row))
        
        # 如果是第一行，添加出参示例
        if i == 0 and response_example:
            row_dict["出参示例"] = response_example
        
        data.append(row_dict)
    
    result["headers"] = headers
    result["data"] = data
    result["raw_data"] = table_data  # 保存原始数据
    return result

def print_tables_from_json(json_data):
    """将JSON解析结果转换为表格并打印（只打印有问题的内容）"""
    for section in json_data.get("sections", []):
        section_has_errors = False
        
        # 检查章节是否有错误
        for table in section.get("tables", []):
            if "validation_results" in table and table["validation_results"]:
                section_has_errors = True
                break
        
        # 如果章节没有错误，跳过打印
        if not section_has_errors:
            continue
            
        print(f"\n=== 章节: {section['title']} ===")
        
        # 打印章节直接包含的表格（只打印有问题的）
        for table in section.get("tables", []):
            table_type = table.get('table_type', '未知类型')
            table_category = table.get('table_category', '未知分类')
            validation_results = table.get("validation_results", {})
            
            # 检查是否有错误
            if not validation_results:
                continue
                
            print(f"\n表格类型: {table_type} ({table_category})")
            
            # 输出标准检查结果
            print("标准检查结果:")
            for col_name, col_results in validation_results.items():
                # 处理表3-的错误格式
                if isinstance(col_results, dict):
                    # 表3-的错误格式：{"rule_name": [errors]}
                    for rule_name, rule_errors in col_results.items():
                        # 汇总相同错误消息的行号和值
                        error_groups = {}
                        for error in rule_errors:
                            msg = error["message"]
                            if msg not in error_groups:
                                error_groups[msg] = []
                            error_groups[msg].append(f"行{error['row']} (值: {error['value']})")
                        
                        # 打印分组后的错误
                        for msg, rows in error_groups.items():
                            print(f"  - {col_name} ({rule_name}): {msg}")
                            print(f"    位置: {', '.join(rows)}")
                elif col_results != "所有数据符合规范":
                    # 处理表2-的错误格式：{"rule_name": [errors]} 或字符串
                    # 汇总相同错误消息的行号和值
                    error_groups = {}
                    for error in col_results:
                        msg = error["message"]
                        if msg not in error_groups:
                            error_groups[msg] = []
                        error_groups[msg].append(f"行{error['row']} (值: {error['value']})")
                    
                    # 打印分组后的错误
                    for msg, rows in error_groups.items():
                        print(f"  - {col_name}: {msg}")
                        print(f"    位置: {', '.join(rows)}")
            
            # 打印表格数据
            if "data" in table and table["data"]:
                headers = table.get("headers", [])
                data = table["data"]
                
                # 创建DataFrame
                if headers and all(isinstance(row, dict) for row in data):
                    df = pd.DataFrame(data)
                    if not df.empty:
                        print(tabulate(df, headers='keys', tablefmt='grid'))
                    else:
                        print("（空表格）")
                else:
                    print("（无表格数据）")
            else:
                print("（无表格数据）")

if __name__ == '__main__':
    try:
        # 获取当前脚本所在目录
        current_dir = os.path.dirname(os.path.abspath(__file__))
        doc_path = os.path.join(current_dir, '服务设计说明书.docx')
        print(f"文档完整路径: {doc_path}")
        
        if not os.path.exists(doc_path):
            raise FileNotFoundError(f"文档文件不存在: {doc_path}")
            
        json_data = read_docx_tables(doc_path)  
        output_path = os.path.join(
            current_dir,
            f"{os.path.splitext(os.path.basename(doc_path))[0]}_output.json"
        )
        print(f"生成文件路径：{output_path}")
        
        # 检查输出内容
        with open(output_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
            print("\n=== 文档解析结果验证 ===")
            print(f"总章节数: {len(data['sections'])}")
            for i, section in enumerate(data["sections"]):
                print(f"\n章节 {i+1}: {section['title']}")
                print(f"  表格数: {len(section.get('tables', []))}")
                
                for j, table in enumerate(section.get('tables', [])):
                    table_type = table.get('table_type', '未知类型')
                    table_category = table.get('table_category', '未知分类')
                    print(f"  表格{j+1}: {table_type} ({table_category})")
            
            print(f"输出内容统计: 章节数={len(data['sections'])}, 表格总数={sum(len(s.get('tables', [])) for s in data['sections'])}")
            
        print("\n\n=== 解析结果表格打印（仅显示有问题内容）===")
        print_tables_from_json(json_data)
        
    except Exception as e:
        print(f"处理文档时出错: {str(e)}")
        import traceback
        traceback.print_exc()